let createError = require('http-errors');
let express = require('express');
let ejs=require('ejs');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let cors = require('cors')
let JWT = require('./utils/jwt');



let indexRouter = require('./routes/index');
let usersRouter = require('./routes/users');
let subUserRouter = require('./routes/subUser');
let subInfoRouter = require('./routes/subInfo');
let subRouter = require('./routes/sub');


let app = express();
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// //设置html模板渲染引擎
// app.engine('html',ejs.__express);
// //设置渲染引擎为html
// app.set('view engine','html');
app.use(cors())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function (req, res, next) {
  let whiteList = ['/loginIn']
  if(whiteList.includes(req.originalUrl)){
    next()
  }else{
    if (!req.headers.authorization)next(createError(403))
    let token = req.headers?.authorization.slice(7)
    JWT.verifyToken(token,res,next)
  }
})

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/subUser', subUserRouter);
app.use('/subInfo', subInfoRouter);
app.use('/sub',subRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(500).send({
    code: 500,
    message: '操作失败!'
  });
});


module.exports = app;
